<template>
  <div class="content">
    <!-- 调用组件  -->
    <perfect-scrollbar class="x-my-app">
      <draggable
        v-model="list"
        @start="onStart"
        @end="onEnd"
        item-key="id"
        class="x-draggable"
        :disabled="!isEdit"
        :style="{ width: comWidth }"
      >
        <template #item="{ element }">
          <div>
            <div :class="isEditCss" v-if="element.type != 'add'">
              <!-- 删除按钮 -->
              <a-button
                type="link"
                shape="circle"
                size="small"
                class="x-close"
                v-if="isEdit"
                @click="clickeDelete(element)"
              >
                <template #icon><close-outlined /></template>
              </a-button>
              <!-- 图标 -->
              <div class="x-ico" @click="gotoDetails(element)">
                <a-image
                  :preview="false"
                  :width="45"
                  :height="45"
                  :src="element.ico"
                  :fallback="fallback"
                  style="border-radius: 8px"
                />
              </div>

              <a-tooltip placement="bottom">
                <template #title>
                  <span>{{ element.name }}</span>
                </template>
                <div class="x-name">{{ element.name }}</div>
              </a-tooltip>
            </div>
            <!-- 添加按钮 -->
            <a-button
              type="link"
              class="x-add"
              v-if="element.type == 'add' && !isEdit"
              @click="clickeAdd"
            >
              <template #icon><plus-outlined /></template>
            </a-button>
          </div>
        </template>
      </draggable>
    </perfect-scrollbar>

    <a-button type="link" shape="circle" size="large" class="x-button">
      <template #icon>
        <check-outlined v-if="isEdit" @click="clickeEditOk" />
        <edit-outlined v-else @click="clickEdit" />
      </template>
    </a-button>
    <!-- 弹窗 -->
    <a-modal
      :width="400"
      v-model:visible="visible"
      title="添加网站"
      @ok="handleOk"
    >
      <a-spin :spinning="confirmLoading">
        <a-form
          name="form"
          ref="formRef"
          :model="formState"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 19 }"
          :rules="reactive"
        >
          <a-form-item label="网址" name="url">
            <a-input-group compact>
              <a-input
                v-model:value="formState.url"
                placeholder="请输入网址"
                style="width: calc(100% - 64px)"
              />
              <a-button type="primary" @click="submitURLHandler">校验</a-button>
            </a-input-group>
          </a-form-item>

          <a-form-item label="名称" name="name">
            <a-input v-model:value="formState.name" placeholder="请输入名称" />
          </a-form-item>
          <a-form-item label="图标" name="ico">
            <a-input v-model:value="formState.ico" placeholder="请输入图标" />
          </a-form-item>
        </a-form>
      </a-spin>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRaw } from "vue";
import { message } from "ant-design-vue";

import {
  EditOutlined,
  CheckOutlined,
  CloseOutlined,
  PlusOutlined,
} from "@ant-design/icons-vue";

import draggable from "vuedraggable";
import { getItem, setItem, keys } from "@/utils/localStorage";
import { realmName } from "@/utils/url";
import { submitURL } from "@/api/api";

interface Values {
  id?: string;
  url?: string;
  ico?: string;
  name?: string;
  type?: string;
}
export default defineComponent({
  name: "MyApplicationCom",
  components: {
    draggable,
    EditOutlined,
    CheckOutlined,
    CloseOutlined,
    PlusOutlined,
  },
  props: {},
  setup() {
    const formRef = ref<any>();

    const onOk = (): Promise<Values> => {
      return formRef.value.validateFields();
    };
    return {
      formRef,
      onOk,
    };
  },

  data() {
    const list: Array<Values> = [];
    const formState: Values = {};
    return {
      isEdit: false, // 是否编辑
      drag: false,
      visible: false, // 添加弹窗
      confirmLoading: false, // 加载
      list,
      formState,
      reactive: {
        url: [{ required: true, message: "请输入网址" }],
        ico: [{ required: true, message: "请输入图标" }],
        name: [{ required: true, message: "请输入名称" }],
      },
      fallback:
        "",
    };
  },
  created() {
    this.getMyApplocatList();
  },
  beforeUnmount() {
    //
  },
  computed: {
    //计算宽度
    comWidth(): string {
      let leng = this.list.length;
      let y = Math.ceil(leng / 3);
      // 判断是否小于
      if (y <= 11) {
        return "880px";
      }
      // console.log();
      // 大于 (900 / 11) * y
      let l = Math.ceil((900 / 11) * y);
      //  有余 y + 1
      return l + "px";
    },
    // 是否编辑
    isEditCss(): string {
      if (this.isEdit) {
        return "item animate-bounce-up";
      }
      return "item";
    },
  },
  methods: {
    // 获取我的应用列表
    getMyApplocatList() {
      let list = getItem(keys.MyApplocat);
      if (!list) {
        list = [];
      }
      let arr: Array<any> = [];
      for (let item of list) {
        if (item["type"] == "add") {
          continue;
        }
        arr.push(item);
      }
      arr.push({
        id: "-1",
        type: "add",
      });
      this.list = arr;
    },
    // 保存我的应用列表
    setMyApplocatlist(list: Array<any>) {
      setItem(keys.MyApplocat, list);
      this.getMyApplocatList();
    },
    //开始拖拽事件
    onStart() {
      this.drag = true;
    },
    //拖拽结束事件
    onEnd() {
      this.drag = false;
    },
    // 编辑应用列表
    clickEdit() {
      this.isEdit = true;
    },
    // 完成编辑
    clickeEditOk() {
      this.isEdit = false;
      let arr: Array<Values> = [];
      // 处理添加按钮
      for (let item of this.list) {
        if (item["type"] == "add") {
          continue;
        }
        arr.push(item);
      }
      this.setMyApplocatlist(arr);
    },
    // 删除应用
    clickeDelete(obj: any) {
      let arr: Array<Values> = [];
      for (let item of this.list) {
        if (item["id"] == obj["id"]) {
          continue;
        }
        arr.push(item);
      }
      this.list = arr;
    },
    // 添加应用
    clickeAdd() {
      this.visible = true;
      this.formState = { id: "", url: "", ico: "", name: "", type: "" };
    },
    // 添加完成
    handleOk() {
      this.onOk()
        .then((values: Values) => {
          console.log("校验成功：", values);
          let url = realmName(values.url || "");
          values.ico = "http://" + url + "/favicon.ico";
          values.name = url;
          values.id = this.list.length + 1 + "";
          this.list.push(values);
          this.visible = false;
          this.clickeEditOk();
        })
        .catch(() => {
          console.log("校验失败：");
        });
    },
    // 跳转详情
    gotoDetails(obj: Values) {
      if (obj.url) {
        window.open(obj.url || "");
      }
    },

    // 校验网址
    submitURLHandler() {
      let formState: Values = this.formState;
      if (!formState.url) {
        return message.warning("请添加网址");
      }
      this.confirmLoading = true;
      submitURL(formState)
        .then((res: any) => {
          this.confirmLoading = false;
          const data = res.data;
          if (data.code != 200) {
            return message.error(data.message);
          }
          const result = data.result;
          formState.ico = result.href;
          formState.name = result.name;
          this.formState = formState;
        })
        .catch(() => {
          this.confirmLoading = false;
        });
    },
  },
});
</script>

<style scoped lang="less">
.content {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  position: relative;

  .x-my-app {
    width: 900px;
    height: 300px;
    padding: 10px;
    box-sizing: border-box;

    background: white;
    background: linear-gradient(
      to right bottom,
      rgba(255, 255, 255, 0.1),
      rgba(255, 255, 255, 0.1)
    );
    backdrop-filter: blur(1px);
    z-index: 1;
    border-radius: 10px;
    box-shadow: 0 0 1rem rgba(0, 0, 0, 0.2);

    position: relative;
  }

  .x-button {
    background: white;
    background: linear-gradient(
      to right bottom,
      rgba(255, 255, 255, 0.1),
      rgba(255, 255, 255, 0.1)
    );
    backdrop-filter: blur(1em);
    box-shadow: 0 0 1rem rgba(0, 0, 0, 0.2);
    // border-radius: 50%;
    position: absolute;
    top: -30px;
    right: 18%;
    z-index: 10;
    color: white;
  }

  .x-draggable {
    // width: 1000px;
    // background: red;
  }

  .x-my-app::after {
    content: "";
    clear: both;
    display: table;
  }

  /*被拖拽对象的样式*/
  .item {
    cursor: pointer;
    float: left;
    margin: 5px;
    padding: 5px;
    display: flex;
    flex-direction: column;
    align-items: center;
    border-radius: 5px;
    position: relative;

    width: 70px;
    height: 80px;

    .x-close {
      position: absolute;
      top: -8px;
      right: -3px;
      z-index: 10;
      color: white;
      background: white;
      background: linear-gradient(
        to right bottom,
        rgba(255, 255, 255, 0.1),
        rgba(255, 255, 255, 0.1)
      );
      backdrop-filter: blur(1em);
      box-shadow: 0 0 1rem rgba(0, 0, 0, 0.2);
    }

    .x-name {
      width: 60px;
      margin-top: 2px;

      font-size: 13px;
      font-weight: normal;
      color: white;
      text-align: center;

      /*1. 先强制一行内显示文本*/
      white-space: nowrap;
      /*2. 超出的部分隐藏*/
      overflow: hidden;
      /*3. 文字用省略号替代超出的部分*/
      text-overflow: ellipsis;
    }

    .x-ico {
      background-color: white;
      border-radius: 8px;
    }
  }

  .x-add {
    cursor: pointer;
    float: left;
    margin: 5px;
    padding: 5px;
    display: flex;
    flex-direction: column;
    align-items: center;
    border-radius: 5px;
    position: relative;
    width: 70px;
    height: 70px;

    background: white;
    background: linear-gradient(
      to right bottom,
      rgba(255, 255, 255, 0.6),
      rgba(255, 255, 255, 0.3)
    );
    backdrop-filter: blur(2em);
    display: flex;
    align-items: center;
    justify-content: center;

    .anticon-plus {
      font-size: 30px;
      color: white;
    }
  }

  .item:hover {
    background-color: rgba(232, 232, 233, 0.2);
  }
  /*选中样式*/
  .chosen {
    border: solid 2px #3089dc !important;
  }
}

.animate-bounce-up {
  cursor: move !important;
  // animation: roundRule 0.5s 0s infinite;
  // -webkit-animation: roundRule 0.5s 0s infinite;
}

.animate-bounce-up:hover {
  animation: none;
  -webkit-animation: none;
}

@keyframes roundRule {
  0%,
  100% {
    transform: rotate(-15deg);
    -webkit-transform: rotate(-15deg);
  }
  50% {
    transform: rotate(15deg);
    -webkit-transform: rotate(15deg);
  }
}
</style>
